﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;


namespace CookieTerm
{
    public class EditableListBox : ListBox
    {
        TextBox editBox = new TextBox();
        bool needToSave;

        public EditableListBox()
        {
            this.editBox.Hide();
            editBox.KeyPress += new KeyPressEventHandler(editBox_KeyPress);
            editBox.LostFocus += new EventHandler(editBox_LostFocus);
            Controls.Add(this.editBox);
        }

        public void ReloadFromDataSource()
        {
            if (BindingContext != null && DataSource != null)
            {
                ((CurrencyManager)BindingContext[DataSource]).Refresh();
            }
        }

        protected override void OnDoubleClick(EventArgs e)
        {
            base.OnDoubleClick(e);

            if (SelectedItem != null)
            {
                StartEditing();
            }
        }

        public void StartEditing()
        {
            this.needToSave = true;
   
            editBox.Bounds = GetItemRectangle(SelectedIndex);
            editBox.Font = Font;
            editBox.BackColor = BackColor;
            editBox.ForeColor = ForeColor;
            editBox.Text = SelectedValue.ToString();

            editBox.Show();
            editBox.Focus();
            editBox.SelectAll();
        }

        void editBox_LostFocus(object sender, EventArgs e)
        {
            if (this.needToSave)
            {
                Save(editBox.Text);
            }
            this.editBox.Hide();
        }

        private void Save(string value)
        {
            object target = this.SelectedItem;
            string property = this.ValueMember;

            if (target != null && !string.IsNullOrEmpty(property))
            {
                PropertyInfo pi = target.GetType().GetProperty(property);
                if (pi != null)
                {
                    pi.SetValue(target, value, null);
                    ReloadFromDataSource();
                }
            }
        }

        void editBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                this.editBox.Hide();
            }
            if (e.KeyChar == 27) // ESC
            {
                e.Handled = true;
                this.needToSave = false;
                this.editBox.Hide();
            }
        }
    }
}
